﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System;
using WidgetsDesign.API.Models;
using WidgetsDesign.API.Services;
using static WidgetsDesign.API.Controllers.UserController;

[Route("api/[controller]/[action]")]
[ApiController]
public class UploadFileController : ControllerBase
{
    private readonly IWebHostEnvironment _webHostEnvironment;
    private readonly IUserRepository _userRepository;
    private readonly IUploadFileRepository _uploadFileRepository;
    private readonly IMapper _Mapper;
    private IConfiguration _configuration { get; set; }
    public UploadFileController(IUserRepository userRepository, IMapper mapper, IConfiguration config, IWebHostEnvironment webHostEnvironment, IUploadFileRepository uploadFileRepository)
    {
        _configuration = config;
        _webHostEnvironment = webHostEnvironment;
        _userRepository = userRepository;
        _Mapper = mapper;
        _uploadFileRepository = uploadFileRepository;
    }
    [HttpPost("{UserId}")]
    public async Task<IActionResult> UploadFile(IFormFile formFile, [FromRoute] int UserId)
    {
        var UserInfo = await _userRepository.GetUserInfoById(UserId);
        if (UserInfo == null)
        {
            return Ok(new { code = 0, message = "不存在该用户" });
        }
        var fileSize = formFile.Length;
        if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
        {
            return Ok(new { code = 0, message = "上传的文件不能大于10M" });
        }
        var currentDate = DateTime.Now;
        var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名
        var saveName = UserId + "_" + currentDate.ToString("yyMMddHHmmss") + currentDate.Millisecond.ToString() + fileExtension;
        string web_path = _webHostEnvironment.WebRootPath;
        string folderPath = Path.Combine("wwwroot", "Images");

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        string path = Path.Combine(folderPath, saveName);
        using (var fs = System.IO.File.Create(path))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        var newFile = new UploadFile
        {
            Uuid = Guid.NewGuid(),
            UserId = UserId,
            CreateTime = DateTime.Now,
            FileUrl = "Images/" + saveName,
            FileSize = fileSize,
        };
        _uploadFileRepository.CreateFile(newFile);
        await _uploadFileRepository.SaveAsync();
        return Ok(new { code = 200, message = newFile.Uuid });
    }

    /// <summary>
    /// 上传头像
    /// </summary>
    /// <param name="formFile"></param>
    /// <param name="UserId"></param>
    /// <returns></returns>
    [HttpPost("{uuid}")]
    public async Task<IActionResult> UploadAvatar(IFormFile formFile, [FromRoute] Guid uuid)
    {
        var UserInfo = await _userRepository.GetUserInfoByUuid(uuid);
        if (UserInfo == null)
        {
            return Ok(new { code = 0, message = "不存在该用户" });
        }
        var fileSize = formFile.Length;
        if (fileSize > 1024 * 1024 * 2) //2M TODO:(1mb=1024X1024b)
        {
            return Ok(new { code = 0, message = "上传的文件不能大于5M" });
        }
        var currentDate = DateTime.Now;
        var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名
        var saveName = uuid + fileExtension;
        string web_path = _webHostEnvironment.WebRootPath;
        string folderPath = Path.Combine("wwwroot", "Avatar");

        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        string path = Path.Combine(folderPath, saveName);
        using (var fs = System.IO.File.Create(path))
        {
            await formFile.CopyToAsync(fs);
            await fs.FlushAsync();
        }
        var url = $"Avatar/{saveName}";
        await _userRepository.UploadAvatar(uuid, url);
        await _userRepository.SaveAsync();
        return Ok(new { code = 200, message = "上传成功" });
    }
}
